<template>
  <div class="hello">
    <h3>油耗信息</h3>
    <p>提示：根据输入的数据实时计算出结果</p>
    <el-input placeholder="请输入今日油价" v-model="oilPricesToday" clearable></el-input>
    <el-input placeholder="请输入行驶里程数" v-model="drivingMileage" clearable></el-input>
    <el-input placeholder="请输入每百公里油耗" v-model="FuelConsumptionPer100km" clearable></el-input>

    <ul>
      <li>每公里油价:{{result.oilPricePerKilometer | numFilter}}元</li>
      <li>行驶路程油价:{{result.drivingDistanceOilPrice | numFilter}}元</li>
      <li>行驶路程油耗:{{result.fuelConsumptionInDrivingDistance | numFilter}}升</li>
    </ul>

    <el-row>
      <el-button type="danger" plain @click="empty">清空数据</el-button>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "OilConsumption",
  data() {
    return {
      oilPricesToday: "", // 今日油价
      drivingMileage: "", // 行驶里程数
      FuelConsumptionPer100km: "", // 每百公里油耗
      result: {
        drivingDistanceOilPrice: 0, // 行驶路程油价
        oilPricePerKilometer: 0, // 每公里油价
        fuelConsumptionInDrivingDistance: 0 // 行驶路程油耗
      }
    };
  },
  filters: {
    numFilter(value) {
      // 截取当前数据到小数点后两位
      let realVal = parseFloat(value).toFixed(2);
      return realVal;
    }
  },
  watch: {
    oilPricesToday() {
      if (this.isEmpty()) {
        this.deal();
      }
    },
    drivingMileage() {
      if (this.isEmpty()) {
        this.deal();
      }
    },
    FuelConsumptionPer100km() {
      if (this.isEmpty()) {
        this.deal();
      }
    }
  },
  methods: {
    deal() {
      // 行驶路程油价 = (每百公里油耗/100)*行驶里程数*今日油价
      this.result.drivingDistanceOilPrice =
        (this.FuelConsumptionPer100km / 100) *
        this.drivingMileage *
        this.oilPricesToday;
      // 每公里油价 = 行驶路程油价/行驶里程数
      this.result.oilPricePerKilometer =
        this.result.drivingDistanceOilPrice / this.drivingMileage;
      // 行驶路程油耗 = (每百公里油耗/100)*行驶里程数
      this.result.fuelConsumptionInDrivingDistance =
        (this.FuelConsumptionPer100km / 100) * this.drivingMileage;
    },
    empty() {
      this.oilPricesToday = "";
      this.drivingMileage = "";
      this.FuelConsumptionPer100km = "";
      this.result = {
        drivingDistanceOilPrice: 0, // 行驶路程油价
        oilPricePerKilometer: 0, // 每公里油价
        fuelConsumptionInDrivingDistance: 0 // 行驶路程油耗
      }
    },
    isEmpty() {
      if (
        this.oilPricesToday == "" ||
        this.drivingMileage == "" ||
        this.FuelConsumptionPer100km == ""
      ) {
        return false;
      }
      return true;
    }
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="stylus">
h3 {
  margin: 20px auto;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin: 0 10px;
  text-align: left;
}

a {
  color: #42b983;
}

.el-input {
  margin-bottom: 10px;
}
</style>
